#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>

int main(int argc, char *argv[])
{
    int fd, retvalue;
    char *filename;
    char readbuf[100];
    char *write_data;  // 指向要写入的数据

    // 修改：要求 3 个参数（读操作时 argv[3] 可选，但写必须有）
    if (argc < 3) {
        printf("Error Usage!\n");
        printf("Usage: %s <dev_file> <1:read, 2:write> [write_data]\n", argv[0]);
        return -1;
    }

    filename = argv[1];

    // 打开设备文件
    fd = open(filename, O_RDWR);
    if (fd < 0) {
        printf("Can't open file %s\n", filename);
        return -1;
    }

    if (atoi(argv[2]) == 1) {
        // 读操作
        retvalue = read(fd, readbuf, sizeof(readbuf) - 1);
        if (retvalue < 0) {
            printf("Read from %s failed!\n", filename);
        } else if (retvalue == 0) {
            printf("No data read.\n");
        } else {
            readbuf[retvalue] = '\0';  // 安全添加结束符
            printf("Read data: %s\n", readbuf);
        }
    }
    else if (atoi(argv[2]) == 2) {
        // 写操作：必须提供第 3 个参数
        if (argc < 4) {
            printf("Please provide data to write!\n");
            close(fd);
            return -1;
        }

        write_data = argv[3];  // 从命令行获取要写入的数据

        retvalue = write(fd, write_data, strlen(write_data));  // 只写有效长度
        if (retvalue < 0) {
            printf("Write to %s failed!\n", filename);
        } else {
            printf("Write %d bytes: %s\n", retvalue, write_data);
        }
    }
    else {
        printf("Operation not supported! Use 1 to read, 2 to write.\n");
    }

    // 关闭设备
    close(fd);
    return 0;
}